//
//  YZXPictureView.swift
//  YZXWeibo
//
//  Created by 叶周翔 on 16/7/24.
//  Copyright © 2016年 叶周翔. All rights reserved.
//

import UIKit
/// 保存微博中的图片
/// 最大的行和列数
let maxNum:Int = 3

/// 微博配图的每一张图片的宽和高
let picureWH:CGFloat = (UIScreen.mainScreen().bounds.size.width - 2*CellMargin - CGFloat((maxNum - 1))*itemPadding) / CGFloat(maxNum)

 /// 图片之间的距离
let itemPadding: CGFloat  = 4

class YZXPictureView: UIView, SDPhotoBrowserDelegate {
     var imageViews = [UIImageView]()
    
    var imageURLs:[NSURL]?{
        didSet{
            // 布局每一张图片
            let size = self.layoutImages(imageURLs)
            // 更新约束
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(size)
            }
            
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
//        self.backgroundColor = UIColor.redColor()
        self.setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func layoutImages(imageURL:[NSURL]?) -> CGSize{
        let count = imageURLs?.count ?? 0
        /// 总列数 默认3列
        var numberOfColumn = maxNum
        if count == 1 {
            numberOfColumn = 1
        } else if count == 2 || count == 4 {
            numberOfColumn = 2
        }
        
        for (index,imageView) in imageViews.enumerate(){
            
            if index >= count{
                imageView.hidden = true
            }else{
                imageView.hidden = false
                // 计算每一张图片所在的列
                let col = index % numberOfColumn
                // 所在的行数
                let row = index / numberOfColumn
                // 设置frame
                let x = CGFloat(col) * (picureWH+itemPadding)
                let y = CGFloat(row) * (picureWH + itemPadding)
                imageView.frame = CGRect(x: x, y: y, width: picureWH, height: picureWH)
                // 下载图片
                let url = imageURL![index]
                //
                imageView.sd_setImageWithURL(url)
            }
        }
        if count == 0{
            return CGSizeZero
        }
        
        // 计算宽度 = 总列数*图片宽度+（总列数-1）*图片间距
        let width = CGFloat(numberOfColumn) * picureWH + CGFloat((maxNum-1)) * itemPadding
        // 计算总行数
        let numRow = (count+numberOfColumn-1) / numberOfColumn
        
        // 计算高度 = 总行数 * 图片高度 + （总行数-1）*图片的间距
        let height = CGFloat(numRow) * picureWH + CGFloat((maxNum-1)) * itemPadding
        return CGSize(width: width, height: height)
    }
    private func setUpUI(){
        for i in 0..<9{
            let imageView = UIImageView()
//            imageView.backgroundColor = UIColor.randomColor()
            // 填充样式
            imageView.contentMode = UIViewContentMode.ScaleToFill
//            imageView.layer.masksToBounds = true
            
            imageView.userInteractionEnabled = true
            // 添加点击事件 添加手势
            
            imageView.tag = i
            let tap = UITapGestureRecognizer(target: self, action: "imageViewDidClick:")
            imageView.addGestureRecognizer(tap)
            
            // 添加到父控件
            self.addSubview(imageView)
            // 添加到图片数组中
            imageViews.append(imageView)
        }
    }
    
    //MARK:- 图片点击事件
    @objc private func imageViewDidClick(tap:UITapGestureRecognizer) {
        // 获取点击的图片
        let imageView = tap.view!
        let brower = SDPhotoBrowser()
        brower.sourceImagesContainerView = self
        brower.imageCount = imageURLs?.count ?? 0
        brower.currentImageIndex = imageView.tag
        brower.delegate = self
        // 展示图片浏览器
        brower.show()
    }
    
}


extension YZXPictureView {
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        let imageView = imageViews[index]
        return imageView.image
    }
    
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        let urlString = imageURLs![index].absoluteString
        // 换成大图
        let largeImage = urlString.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
        return NSURL(string: largeImage)
    }
    
}